package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Reply;
import cn.wolfcode.domain.User;
import cn.wolfcode.mapper.ReplyMapper;
import cn.wolfcode.service.IReplyService;
import cn.wolfcode.service.IUserService;
import cn.wolfcode.vo.ReplyVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class ReplyServiceImpl extends ServiceImpl<ReplyMapper, Reply> implements IReplyService {

    @Autowired
    private IUserService userService;

    @Override
    public List<ReplyVo> rank() {
        //select reply_user_id,COUNT('reply_user_id') from reply
        //GROUP BY reply_user_id
        QueryWrapper<Reply> wrapper = new QueryWrapper<>();
        wrapper.select("reply_user_id,COUNT('reply_user_id') count")
                .groupBy("reply_user_id")
                .orderByDesc("count");
        List<Map<String, Object>> list = super.listMaps(wrapper);
        ArrayList<ReplyVo> replyVos = new ArrayList<>();
        for (Map<String, Object> map : list) {
            Long userId = Long.parseLong(map.get("reply_user_id").toString());
            Integer count = Integer.parseInt(map.get("count").toString());
            ReplyVo vo = new ReplyVo();
            User user = userService.getById(userId);
            vo.setUser(user);
            vo.setCount(count);
            replyVos.add(vo);
        }
        return replyVos;
    }
}
